package com.xs.jmb2c.controller;

import com.xs.jmb2c.common.Result;
import com.xs.jmb2c.dto.MemberBindAccountDTO;
import com.xs.jmb2c.dto.MemberLoginDTO;
import com.xs.jmb2c.dto.MemberRegisterDTO;
import com.xs.jmb2c.dto.MemberUpdatePasswordDTO;
import com.xs.jmb2c.entity.Member;
import com.xs.jmb2c.service.MemberService;
import com.xs.jmb2c.vo.MemberInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author root
 * @since 2025-07-01
 */
@Slf4j
@RestController
@Tag(name="会员管理")
@RequestMapping("/member")
public class MemberController {
    @Resource
    private MemberService memberService;

    @Autowired
    private StringRedisTemplate redisTemplate;    // RedisTemplate

    @Operation(summary = "用户登录接口", description = "用户登录接口")
    @PostMapping("login")
    public Result<String> login(@RequestBody MemberLoginDTO memberLoginDTO) {
        String token = memberService.login(memberLoginDTO);
        return Result.success(token);
    }

    @GetMapping("info")
    public Result<MemberInfoVO> info() {
        MemberInfoVO member = memberService.info();
        return Result.success(member);
    }

    @PutMapping("updatePassword")
    public Result<Object> updatePassword(@RequestBody MemberUpdatePasswordDTO memberUpdatePasswordDTO){
        memberService.updatePassword(memberUpdatePasswordDTO);
        return Result.success();
    }

    @PostMapping("register")
    public Result<Member> register(@RequestBody MemberRegisterDTO memberRegisterDTO){
        Member member = memberService.register(memberRegisterDTO);
        return Result.success(member);
    }

    @PostMapping("sendCode")
    public Result<Object> sendCode(@RequestBody MemberRegisterDTO memberRegisterDTO){
        Random random = new Random();
        String code = random.nextInt(888888) + 100000 + "";
        //将验证码写入redis
        redisTemplate.opsForValue().set("code",code);
        log.info("验证码:{}",code);
        return Result.success();
    }

    @DeleteMapping()
    public Result<Object> delete(List<Long> ids){
        this.memberService.removeBatchByIds(ids);
        return Result.success();
    }

    @PutMapping("bindPhoneOrEmailOrOpenId")
    public Result<Object> bindPhoneOrEmailOrOpenId(@RequestBody MemberBindAccountDTO memberBindAccountDTO){
        //幂等接口
        log.info("memberBindAccountDTO: {}",memberBindAccountDTO);
        this.memberService.bindPhoneOrEmailOrOpenId(memberBindAccountDTO);
        return Result.success();
    }
}